package main

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

func main() {
	for {
		reader := bufio.NewReader(os.Stdin)
		fmt.Print("清输入你要整理按最后修改时间月份分类的目录路径:")
		dir, _ := ReadInputStr(reader)
		//获取绝对路径
		dir, _ = filepath.Abs(dir)
		if !IsDir(dir) {
			fmt.Println("目录:" + dir + " 不存在，清重新输入")
			continue
		}

		fmt.Println("确定要将目录：" + dir + " 下的所有文件移动到按时间月份分类目录？(y/n)")
		confirmB, _ := ReadInputStr(reader)
		if confirmB != "y" {
			continue
		}
		//windows 环境下是\r\n
		dir = strings.Replace(dir, "\n", "", -1)
		dir = strings.Replace(dir, "\r", "", -1)

		err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
			if info == nil {
				return nil
			}
			if path != dir && info.IsDir() {
				return filepath.SkipDir
			}
			if info.IsDir() {
				if path == dir {
					return nil
				} else {
					return filepath.SkipDir
				}
			}
			fmt.Println("文件:" + info.Name() + " 最后修改时间:" + info.ModTime().Format("2006-01-02 15:04:05"))
			yearMonthDir := info.ModTime().Format("2006-01")
			newPathDir := dir + "\\" + yearMonthDir
			if !IsDir(newPathDir) {
				_ = os.Mkdir(newPathDir, os.ModePerm)
			}
			newPath := newPathDir + "\\" + info.Name()
			fmt.Println("移动文件:" + info.Name() + " -> " + newPathDir)
			//移动文件操作
			moveErr := os.Rename(path, newPath)
			if moveErr != nil {
				fmt.Println("移动文件：" + info.Name() + " 到：" + newPath + " 失败! " + moveErr.Error())
			}
			return nil
		})
		if err == nil {
			fmt.Println("操作完成，回车退出程序！")
			_, _, _ = reader.ReadLine()
		} else {
			fmt.Println("目录:" + dir + " 读取错误！")
			fmt.Println(err)
		}
		break
	}
}

func IsDir(fileAddr string) bool {
	s, err := os.Stat(fileAddr)
	if err != nil {
		return false
	}
	return s.IsDir()
}

func ReadInputStr(reader *bufio.Reader) (string, error) {
	input, err := reader.ReadString('\n')
	//windows 环境下是\r\n
	input = strings.Replace(input, "\n", "", -1)
	input = strings.Replace(input, "\r", "", -1)
	return input, err
}
